<template>
  <div class="task-all-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList" fromLocation="已完成任务明细导出" :checkedList="ids" :seachData="searchValue" :showExport="true" :exportInfo="exportInfo">
        <template #headerLeft>
          <!-- <div>合计任务：9条 合计任务费用：￥1650 </div> -->
        </template>
        <template #tableBody>
          <a-table size="mini" row-class="task-item" v-model:selected-keys="ids" row-key="id" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" :bordered="{ cell: true }" class="table-two-line" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
              <a-table-column title="任务ID" #cell="{ record }" :width="120">
                <a-space>
                  <div class="highlight cursor">{{ record.code }}</div>
                  <div v-if="record.isSample">
                    <span style="color: #979797" class="icon icon-yangpin"></span>
                  </div>
                </a-space>
              </a-table-column>
              <a-table-column title="产品">
                <a-table-column title="图片" #cell="{ record }" :width="60">
                  <ImgPopover :src="imgUrl(record)">
                    <template #con>
                      <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                    </template>
                  </ImgPopover>
                </a-table-column>
                <a-table-column title="SKU" #cell="{ record }" :width="80">
                  <TextLimit position="top" :rows="1" :val="$extract(record, 'product.sku')" />
                </a-table-column>
                <!-- <a-table-column title="SPU/类目" #cell="{ record }" :width="100">
                  <TextLimit position="top" :rows="1" :val="$extract(record, 'product.spu')" />
                  <TextLimit position="top" :rows="1" :val="$extract(record, 'product.category.name')" />
                </a-table-column> -->
              </a-table-column>
              <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column>
              <a-table-column title="服务内容" #cell="{ record }" :width="120">
                <TextLimit :val="$extract(record, 'taskRequire.serContent')" :rows="3" position="top" />
              </a-table-column>
              <a-table-column title="任务费用" #cell="{ record }" :width="80">
                <div style="color: red">￥{{ record.amtbCost }}</div>
              </a-table-column>
              <a-table-column title="甲方" #cell="{ record }" :width="80">
                <span>{{ $extract(record, 'companyShortName') }}</span>
                <span v-if="$extract(record, 'companyShortName') != $extract(record, 'deductionInfo.consumerAccountUserName')"> - {{ $extract(record, 'deductionInfo.consumerAccountUserName') }}</span>
              </a-table-column>
              <a-table-column title="完成时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtFinish">
                {{ $setTime(record.gmtFinish, 'YYYY-MM-DD HH:mm') }}
              </a-table-column>
              <a-table-column title="接单时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtTake">
                {{ $setTime(record.gmtTake, 'YYYY-MM-DD HH:mm') }}
              </a-table-column>
              <a-table-column title="任务执行周期" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="executeTime">
                {{ transitionTime(record.executeTime) }}
              </a-table-column>
              <a-table-column title="评价" #cell="{ rowIndex, record }" :width="100">
                <TextLimit position="top" :rows="2" :val="record.evaluation" />
              </a-table-column>
              <a-table-column title="子任务" #cell="{ rowIndex, record }" :width="80">
                <div class="task-item-name" :style="{ border: index == record.taskRequire.taskNodeList.length - 1 ? 'none' : '' }" v-for="(item, index) of record.taskRequire.taskNodeList" :key="index">{{ nodeMap[item.nodeType] }}</div>
              </a-table-column>
              <a-table-column title="执行人" #cell="{ rowIndex, record }" :width="80">
                <div class="task-item-name" :style="{ border: index == record.taskRequire.taskNodeList.length - 1 ? 'none' : '' }" v-for="(item, index) of record.taskRequire.taskNodeList" :key="index">{{ $extract(item, 'executer.name') }}</div>
              </a-table-column>
              <a-table-column title="金额" #cell="{ rowIndex, record }" :width="80">
                <div class="task-item-name" :style="{ border: index == record.taskRequire.taskNodeList.length - 1 ? 'none' : '' }" v-for="(item, index) of record.taskRequire.taskNodeList" :key="index">{{ item.amount }}</div>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, onMounted } from 'vue'
  import { getOrganizesUser } from '@/api/system'
  import { findFinishedTask } from '@/api/task'
  import { nodeMap } from '../../task/components/setting/map'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import _ from 'lodash-es'

  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }

  const filterItem: any = ref([
    {
      type: 'input_keyword',
      key: 'codeList',
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'companyName',
      keyItems: [
        { label: '甲方', value: 'companyName' },
        // { label: '任务创建人', value: 'createUname' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 160,
    },

    {
      key: 'executerId',
      label: '任务执行人',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },

    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报设计', value: 'POSTER_SHOP_DESIGN' },
        { label: '换钻调色', value: 'CHANGE_DIAMOND_COLOR' },
        { label: '手绘设计', value: 'HAND_DRAWN_DESIGN' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      type: 'keyword_date_range',
      key: 'gmtFinish',
      keyItems: [{ label: '完成时间', value: 'gmtFinish' }],
      keyWidth: '110',
      label: '完成时间',
      value: ref(),
      width: 260,
    },
  ])

  let exportInfo: any = ref({
    title: '已完成任务明细导出',
    type: 'single',
    supportAll: true,
    tabName: '已完成任务明细导出',
    fieldList: [
      {
        group: '基础信息',
        columns: [
          {
            name: '序号',
            key: 'sort',
            keyType: '1',
          },
          {
            key: 'code',
            name: '任务ID',
            keyType: '1',
          },
          {
            key: 'product.productPicList',
            name: '产品图片',
            keyType: '2',
          },
          {
            key: 'product.sku',
            name: '产品SKU',
            keyType: '1',
          },
          {
            key: 'type',
            name: '任务类型',
            keyType: '1',
          },
          {
            key: 'taskRequire.serContent',
            name: '服务内容',
            keyType: '1',
          },
          {
            key: 'amtbCost',
            name: '任务费用',
            keyType: '1',
          },
          {
            key: 'companyShortName',
            name: '甲方',
            keyType: '1',
          },

          {
            key: 'gmtFinish',
            name: '完成时间',
            keyType: '1',
          },
          {
            key: 'gmtTake',
            name: '接单时间',
            keyType: '1',
          },
          {
            key: 'executeTime',
            name: '任务执行周期',
            keyType: '1',
          },
          {
            key: 'evaluation',
            name: '评价',
            keyType: '1',
          },
          {
            key: 'taskNodeList.nodeType',
            name: '子任务',
            keyType: '1',
          },
          {
            key: 'taskNodeList.executer.name',
            name: '执行人',
            keyType: '1',
          },
          {
            key: 'taskNodeList.amount',
            name: '任务金额',
            keyType: '1',
          },
        ],
      },
    ],
    supportTemplate: true,
    templateType: 'FINISHED_TASK_UPLOAD',
    exportApi: 'exportFinishTaskItems',
    excelName: '已完成任务明细导出',
  })

  let tableList = ref([])
  let ids = ref([])
  let loading = ref(false)
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  let searchValue: any = ref({})

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)
    if (searchValue.value.startDate) {
      searchValue.value.startDate = new Date(`${searchValue.value.startDate} 00:00:00`).valueOf()
      searchValue.value.endDate = new Date(`${searchValue.value.endDate} 23:59:59`).valueOf()
    }
    if (searchValue.value.codeList) {
      searchValue.value.codeList = searchValue.value.codeList.split(',')
    } else {
      searchValue.value.codeList = []
    }
    getList()
  }

  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }

  const getUser = async () => {
    let params = {
      depart: false,
      needRole: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    let arr = res?.data?.records || []
    filterItem.value[3].optionItems = arr.map((e: any) => {
      return {
        label: e.userName,
        value: e.id,
      }
    })
  }

  const getList = async () => {
    let params = {
      ...searchValue.value,
      status: 'FINISHED',
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    loading.value = true
    const res: any = await findFinishedTask(params)
    tableList.value = res?.data?.records || []
    pageNation.value.total = res?.data?.total || 0
    loading.value = false
  }

  const transitionTime = (time: number) => {
    if (time < 0) return '--'
    const minutes = Math.floor((time / (1000 * 60)) % 60)
    const hours = Math.floor((time / (1000 * 60 * 60)) % 24)
    const days = Math.floor(time / (1000 * 60 * 60 * 24))
    return (days > 0 ? `${days}天` : '') + (hours > 0 ? `${hours}小时` : '') + (minutes > 0 ? `${minutes}分钟` : '')
  }

  const imgUrl = (data: any) => {
    let arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  onMounted(() => {
    getUser()
    getList()
  })
</script>

<style lang="less" scoped>
  .task-all-con {
    height: calc(100vh - @menuAndTabHeight);
  }

  .task-item-name {
    height: 40px;
    line-height: 40px;
    text-align: center;
    border-bottom: 1px solid #d7d7d7;
    // border-left: 1px solid #d7d7d7;
    // border-bottom: 1px solid #d7d7d7;
  }

  .task-item {
    td {
      &:nth-child(13) {
        .arco-table-cell {
          padding: 0 !important;
        }
      }
    }
  }
</style>
